import React, { PureComponent } from 'react';
import { connect } from 'dva';

import { Row, Col, Card, Form, Input, Select, Button, DatePicker, Badge, Progress } from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './TaskList.less';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
    Object.keys(obj)
        .map(key => obj[key])
        .join(',');
// const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['等待发布', '发布中', '发布成功', '发布异常'];
const statusMap = ['default', 'processing', 'success', 'error'];
const progressMap = ['normal', 'active', 'success', 'exception'];

@connect(({ cutinlog, loading }) => ({
    cutinlog,
    loading: loading.models.cutinlog,
}))
@Form.create()
export default class CutInLog extends PureComponent {
    state = {
        expandForm: false,
        selectedRows: [],
        formValues: {},
    };

    componentDidMount() {
        const { progName } = this.props.match.params;
        
        let payload = {};
        if (progName !== 'init') {
          payload = { progName };
        }
        const { dispatch } = this.props;
        dispatch({
            type: 'cutinlog/fetch',
            payload,
        });
    }
    onFresh = () => {
        const postvalue = this.getFormValue();
        this.props.dispatch({
            type: 'cutinlog/fetch',
            payload: { ...postvalue },
        });
    };
    getFormValue = () => {
        const { form } = this.props;
        let postvalue = {};
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const { entries } = Object;
            for (const [key, value] of entries(fieldsValue)) {
                if (value !== null && value !== undefined) {
                    postvalue[key] = value;
                }
            }
            if (postvalue.date && postvalue.date.length > 0) {
                const startTime = postvalue.date[0].format('YYYY-MM-DD HH:mm:ss');
                const endTime = postvalue.date[1].format('YYYY-MM-DD HH:mm:ss');
                postvalue = {
                    ...postvalue,
                    startTime,
                    endTime,
                };
                delete postvalue.date;
            }
        });
        return postvalue;
    };

    handleStandardTableChange = (pagination, filtersArg, sorter) => {
        const { dispatch } = this.props;
        const postvalue = this.getFormValue();
        const params = {
            page: pagination.current,
            pageSize: pagination.pageSize,
            ...postvalue,
        };
        if (sorter.field) {
            params.sorter = `${sorter.field}_${sorter.order}`;
        }

        dispatch({
            type: 'cutinlog/fetch',
            payload: params,
        });
    };

    handleFormReset = () => {
        const { form, dispatch } = this.props;
        form.resetFields();
        dispatch({
            type: 'cutinlog/fetch',
            payload: {},
        });
    };

    handleSearch = e => {
        e.preventDefault();
        const { dispatch } = this.props;
        const postvalue = this.getFormValue();
        console.log('values', postvalue);
        dispatch({
            type: 'cutinlog/fetch',
            payload: postvalue,
        });
    };

    renderSimpleForm() {
        const { getFieldDecorator } = this.props.form;
        const { progId } = this.props.match.params;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={4} sm={24}>
                        <FormItem>
                            {getFieldDecorator('progName', {
                                rules: [{ required: false, message: '请输入节目名称!' }],
                                initialValue: progId === 'init' ? null : progId,
                            })(<Input placeholder="节目名称" />)}
                        </FormItem>
                    </Col>
                    <Col md={4} sm={24}>
                        <FormItem>
                            {getFieldDecorator('devId', {
                                rules: [{ required: false, message: '请输入设备id!' }],
                            })(<Input placeholder="设备ID" />)}
                        </FormItem>
                    </Col>
                    <Col md={4} sm={24}>
                        <FormItem>
                            {getFieldDecorator('devName', {
                                rules: [{ required: false, message: '请输入设备名称!' }],
                            })(<Input placeholder="设备名称" />)}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem>
                            {getFieldDecorator('date')(
                                <RangePicker
                                    showTime={{ format: 'HH:mm' }}
                                    format="YYYY-MM-DD HH:mm"
                                    placeholder={['开始时间', '结束时间']}
                                    // onChange={onChange}
                                    // onOk={onOk}
                                    style={{ width: '100%' }}
                                />
                            )}
                        </FormItem>
                    </Col>
                    {/* <Col md={3} sm={24}>
                        <FormItem>
                            {getFieldDecorator('pubStatus')(
                                <Select allowClear="true" placeholder="任务状态" style={{ width: '100%' }}>
                                    {status.map((item, index) => (
                                        <Option value={index}>{item}</Option>
                                    ))}
                                </Select>
                            )}
                        </FormItem>
                    </Col> */}
                    <Col md={3} sm={24}>
                        <span className={styles.submitButtons}>
                            <Button type="primary" htmlType="submit" style={{ marginRight: 20 }}>
                                查询
              </Button>
                            <Button type="primary" onClick={this.onFresh}>
                                刷新
              </Button>
                        </span>
                    </Col>
                </Row>
            </Form>
        );
    }

    renderForm() {
        return this.state.expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
    }

    render() {
        // //console.log('task', this.props.task);
        const { cutinlog, loading } = this.props;
        const { selectedRows } = this.state;
        const columns = [
            {
                title: '设备ID',
                dataIndex: 'devId',
            },
            {
                title: '设备名称',
                dataIndex: 'devName',
            },
            {
                title: '节目名称',
                dataIndex: 'progName',
            },
            {
                title: '发布状态',
                dataIndex: 'pubStatus',
                // render(val) {
                //     return <Badge status={statusMap[val]} text={status[val]} />;
                // },
            },

            // {
            //     title: '任务进度',
            //     dataIndex: 'progressRate',
            //     render(val, record) {
            //         const percent = val === null ? 0 : Number(val.split('%')[0]);
            //         //console.log('percent', percent);
            //         return (
            //             <Progress
            //                 percent={percent}
            //                 status={progressMap[record.pubStatus]}
            //                 strokeWidth={6}
            //                 style={{ width: 180 }}
            //             />
            //         );
            //     },
            // },
            {
                title: '任务状态',
                dataIndex: 'statusInfo',
            },
            {
                title: '创建时间',
                dataIndex: 'createTime',
                sorter: true,
            },
            {
                title: '更新时间',
                dataIndex: 'updateTime',
                sorter: true,
            },
        ];

        return (
            <PageHeaderLayout title="任务查询">
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>{this.renderForm()}</div>
                        <StandardTable
                            rowKey="pubId"
                            selectedRows={selectedRows}
                            loading={loading}
                            data={cutinlog}
                            columns={columns}
                            onChange={this.handleStandardTableChange}
                        />
                    </div>
                </Card>
            </PageHeaderLayout>
        );
    }
}
